package com.weiyan.blog.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * @author misterWei
 * @create 2020年01月20号:15点51分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 认证 配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private ClientDetailsService clientDetailsService; //此声明就是ClientDetailsServiceConfigurer 中的客户端配置

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private PasswordEncoder passwordEncoder;




    //令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);
        services.setSupportRefreshToken(true); //支持刷新令牌
        services.setTokenStore(tokenStore); //令牌存储策率

        //增强令牌
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        services.setTokenEnhancer(tokenEnhancerChain);
        services.setAccessTokenValiditySeconds(7200); //令牌有效期 2小时
        services.setRefreshTokenValiditySeconds(259200); //刷新令牌有效期3天
        return services;
    }

    /**
     * 安全策率配置
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
       security.tokenKeyAccess("permitAll()")   // oauth//token_key 公开
                 .checkTokenAccess("permitAll()")  // oauth//check_token 公开
                   .allowFormAuthenticationForClients(); //表单认证(申请令牌)


            }


            @Autowired
            private DataSource dataSource;
    /**
     * 该配置客户端详细信息服务
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
       //基于数据库的存储方式  配置的方式一定是方法级别优先级别高的
        clients.withClientDetails(detailsService(dataSource));
        /* clients.inMemory() //使用内存的方式存储.
                 .withClient("cid") //用来标识客户端的ID
                  .secret(new BCryptPasswordEncoder().encode("secret")) //客户端密钥
                    .resourceIds("rid") //资源列表
                *//**
                 * 五大认证方式
                 * authorization_code : 授权码模式
                 * refresh_token : 这个用来刷新令牌
                 * password   : 密码模式
                 *//*
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit","client_credentials") //该client 允许方法的认证方式.
                        .scopes("all") //read  标识符类似 后期用来鉴权 允许授权范围 --用来限制客户端的访问权限,如果为null 就是可以访问所有
                            .autoApprove(false) //
                              .redirectUris("https://www.baidu.com");  //用于跳转的方式*/
    }

    /**
     * 端点配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) // 认证管理器
                   .authorizationCodeServices(authorizationCodeServices) //授权码服务
                    .tokenServices(tokenServices()) //令牌服务
                      .allowedTokenEndpointRequestMethods(HttpMethod.POST); //支持post 提交验证

    }

    //授权码服务配置
   @Bean
    public AuthorizationCodeServices getAuthorizationCodeServices(DataSource dataSource) {
        return new JdbcAuthorizationCodeServices(dataSource);
    }
   @Bean
    public ClientDetailsService detailsService(DataSource dataSource){
       JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
   }

/*    public static void main(String[] args) {
        String secret = BCrypt.hashpw("secret", BCrypt.gensalt());
        System.out.println(BCrypt.checkpw("secret", secret));
    }*/

}
